<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>长轮询</title>
</head>

<body>
  <h3>服务器端没有数据时，我会一直等待它有数据为止</h3>
  <div id="root"></div>


  <!-- 模板 -->
  <script id="userlist" type="text/html">
    <ul>
      {{each data}}
        <li>{{$value.name}}</li>
      {{/each}}
    </ul>
  </script>
  <!-- art-template模板引擎用在 传统的浏览器打开的html中 -->
  <script src="./js/template-web.js"></script>
  <script>
    let skip = 0;
    ; (function send() {
      let xhr = new XMLHttpRequest;
      xhr.open('get', '/ajax?skip=' + skip, true);
      xhr.send();
      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
          if (xhr.status == 200) {
            // 请求有数据返回，处理dom
            let data = JSON.parse(xhr.responseText);
            skip += data.length;
            let html = document.querySelector('#userlist').innerHTML
            document.querySelector('#root').innerHTML += template.render(html, { data })
          } else if (xhr.status == 204) {
            // 不进行处理
          }
          send()
        }
      }
    })();
  </script>
</body>

</html>